#!/bin/bash
#
#  OpenPom $Revision: 16 $
#  $HeadURL: https://openpom.googlecode.com/svn/trunk/send-order $
#
#  Copyright 2010, Exosec
#  Licensed under GPL Version 2.
#  http://www.gnu.org/licenses/
#
#  $Date: 2010-09-13 10:24:33 +0200 (Mon, 13 Sep 2010) $
#
#
# This bash script is just an exemple,
# you must improve it for you needs
#
# called as: "$EXEC_CMD" "$CMD_FILE" "$cmd" &
# $cmd is multilined
#

# uncomment for debug
# out=/tmp/${0##*/}.$RANDOM
# echo $0 $* > $out
# exec 2>> $out
# set -x

if (( $# != 2 )); then
    logger -p error -t "${0##*/}" -- "Invalid arguments"
    exit 2
fi

MAX_EXTCMD=30  ### MAX EXTERNAL COMMAND
SLEEP_TIME=5   ### SLEEP X SECONDS AFTER MAX_EXTCMD IS REACHED

FIFO="$1" ; shift

if [[ ! -p "${FIFO}" ]] ; then
    logger -p error -t "${0##*/}" -- "${FIFO}: not a named pipe"
    exit 2
fi

send_pipe()
{
    (( $# != 1 )) && return 1

    local order="$1"

    #logger -p error -t "${0##*/}" -- ">>>> $1 (local)"
    echo "${order}" > "${FIFO}" \
        || STATUS=1
}

oIFS="$IFS" ; IFS=$'\n'
set -f; orders=( $1 ); set +f
IFS="${oIFS}"

STATUS=0
cpt=0
for order in "${orders[@]}"; do
    (( cpt++ ))
    IFS='; '
    set -f; set -- ${order}; set +f
    IFS="$oIFS"

    # $1 [1363550322]
    # $2 SCHEDULE_FORCED_SVC_CHECK
    # $3 host
    # $4 PING
    # $5 1363550322

    send_pipe "${order}"

    # pause $SLEEP_TIME every $MAX_EXTCMD entries
    if (( cpt == MAX_EXTCMD )); then
        sleep "${SLEEP_TIME}"
        cpt=0
    fi
done

exit "${STATUS}"
